package top.idetect.client.schedule;

import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/* 使用云端服务后，无需再考虑局域网..*/
@Slf4j
//@Component
public class IpUpdateTask {


    public static List<String> ipList = new ArrayList<>();

    @Scheduled(fixedRate = 1000 * 60 * 10)
    public void ipUpdate(){
        try {
            Enumeration<NetworkInterface> networkInterfaces = NetworkInterface.getNetworkInterfaces();
            ipList.clear();

            // 使用 Pattern 编译正则表达式
            Pattern p = Pattern.compile("((25[0-5]|2[0-4]\\d|((1\\d{2})|([1-9]?\\d)))\\.){3}(25[0-5]|2[0-4]\\d|((1\\d{2})|([1-9]?\\d)))");

            while (networkInterfaces.hasMoreElements()) {
                NetworkInterface networkInterface = networkInterfaces.nextElement();
                if (networkInterface.isUp() && !networkInterface.isLoopback()) {
                    log.info("Interface Name: " + networkInterface.getDisplayName());
                    Enumeration<InetAddress> addresses = networkInterface.getInetAddresses();
                    int i = 0;
                    while (addresses.hasMoreElements()) {
                        InetAddress address = addresses.nextElement();
//                        log.info("  IP Address: " + address.getHostAddress());
                        // 使用 Matcher 进行匹配
                        Matcher m = p.matcher(address.getHostAddress());
                        // 查找匹配的子串
                        if (m.find()) {
                            ipList.add(address.getHostAddress());
                            log.info("IP正则表达式匹配成功！" + address.getHostAddress());
                        }
                    }
                }
            }
        } catch (SocketException e) {
            e.printStackTrace();
        }
    }



}
